﻿using System.ComponentModel;

namespace CI.Models
{
    public class PassThroughPropertyBinding : PropertyBindingBase
    {
        public PassThroughPropertyBinding(INotifyPropertyChanged end1, string end1PropertyName,
                                          INotifyPropertyChanged end2, string end2PropertyName)
            : base(end1, end1PropertyName, end2, end2PropertyName)
        {
        }

        protected override void End2_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            CopyPropertyValue(End2, End1, End2PropertyName, End1PropertyName);
        }

        protected override void End1_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            CopyPropertyValue(End1, End2, End1PropertyName, End2PropertyName);
        }

        private static void CopyPropertyValue(INotifyPropertyChanged from, INotifyPropertyChanged to,
                                              string fromPropertyName, string toPropertyName)
        {
            var fromProp = from.GetType().GetProperty(fromPropertyName);
            var toProp = to.GetType().GetProperty(toPropertyName);

            var val = fromProp.GetValue(from, null);

            // set on toProp!
            toProp.SetValue(to, val, null);
        }
    }
}